package com.hottv.meeting.videomeeting.module.agora;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.hottv.meeting.videomeeting.R;
import com.hottv.meeting.videomeeting.common.MeetingConfig;
import com.hottv.meeting.videomeeting.module.agora.data.MsgInfo;
import com.hottv.meeting.videomeeting.module.agora.data.MsgItem;
import com.hottv.meeting.videomeeting.module.meeting.view.VideoData;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.agora.AgoraAPIOnlySignal;
import io.agora.rtc.RtcEngine;

import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;

/**
 * Created by chengwenqiang on 2019/5/30.
 */

public class AgoraManager {

    private static String LOG_TAG = AgoraManager.class.toString();

    private RtcEngine mRtcEngine;

    private Context mContext;

    private static AgoraManager instance;

    private List<MsgItem> mMsgList = new ArrayList<>();

    private HashMap<Integer, Integer> mUserMap = new HashMap<>();


    private AgoraManager()
    {
        mReadNum = 0;
    }

    public static AgoraManager getInstance(){
        if(instance==null)
        {
            instance = new AgoraManager();
        }

        return  instance;
    }

    public RtcEngine getRtcEngine(){
        return mRtcEngine;
    }

    private  AgoraAPIOnlySignal mAgoraSigAPI;
    public AgoraAPIOnlySignal initSigSdk(Context context)
    {
        mContext = context;
        if(mAgoraSigAPI==null)
        {

            String appId = mContext.getString(R.string.agora_app_id);
            if (TextUtils.isEmpty(appId)) {
                throw new RuntimeException("NEED TO use your App ID, get your own ID at https://dashboard.agora.io/");
            }
            try {
                mAgoraSigAPI = AgoraAPIOnlySignal.getInstance(context, appId);
            } catch (Exception e)
            {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
                throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
            }

        }
        return mAgoraSigAPI;
    }
    public RtcEngine initEngine(Context context,IRtcEngineEventHandler handler) {

        mContext = context;

        if (mRtcEngine == null) {
            String appId = mContext.getString(R.string.agora_app_id);
            if (TextUtils.isEmpty(appId)) {
                throw new RuntimeException("NEED TO use your App ID, get your own ID at https://dashboard.agora.io/");
            }
            try {
                mRtcEngine = RtcEngine.create(mContext, appId, handler);
            } catch (Exception e)
            {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
                throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
            }
            mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
            mRtcEngine.enableVideo();
            mRtcEngine.setLogFile(Environment.getExternalStorageDirectory()
                    + File.separator + mContext.getPackageName() + "/log/agora-rtc.log");

            mRtcEngine.enableDualStreamMode(true);


        }
        return mRtcEngine;
    }

    public void addUser(int userId,int userType)
    {
        if(!mUserMap.containsKey(userId))
        {
            mUserMap.put(userId,userType);
        }
    }

    //第一个进来的是主播，后面进来的是观众
    public void addUser(int userId)
    {
        if(!mUserMap.containsKey(userId))
        {
            if(mUserMap.size()<=1)
            {
                addUser(userId,MeetingConfig.BROADCASTER_TYPE);
            }
            else
            {
                addUser(userId,MeetingConfig.AUDIENCE_TYPE);
            }
        }
    }

    public void setUserType(int userId,int type)
    {
        if(mUserMap.containsKey(userId))
        {
            mUserMap.remove(userId);
        }

        mUserMap.put(userId,type);
    }

    public void removeUser(int userId)
    {
        if(mUserMap.containsKey(userId))
        {
            mUserMap.remove(userId);
        }
    }

    public boolean checkInMap(int userId)
    {
        return mUserMap.containsKey(userId);
    }

    public int setBroastcast()
    {
        for (HashMap.Entry<Integer, Integer> pair : mUserMap.entrySet()) {
            if(pair.getValue() == MeetingConfig.BROADCASTER_TYPE)
            {
                pair.setValue(MeetingConfig.AUDIENCE_TYPE);
            }
        }
        return  0;
    }

    public int getBroastcastId()
    {
        for (HashMap.Entry<Integer, Integer> pair : mUserMap.entrySet()) {
            if(pair.getValue() == MeetingConfig.BROADCASTER_TYPE)
                return pair.getKey();
        }
        return  0;
    }

    public void setBroastcast(int userId)
    {
        for (HashMap.Entry<Integer, Integer> pair : mUserMap.entrySet()) {
            if(pair.getKey()==userId)
            {
                pair.setValue(MeetingConfig.BROADCASTER_TYPE);
            }
            else
            {
                pair.setValue(MeetingConfig.AUDIENCE_TYPE);
            }
        }
    }

    //获取userid
    public List<VideoData> getVideoDataList(int userId,boolean videoFirst)
    {
        List<VideoData> dataList = getAllVideoDataList();
        int brostcastId = getBroastcastId();
        if(userId==brostcastId)
        {
            //如果是主播 视频优先  获取除主播外的所有列表
            if(videoFirst)
            {
               for(int i=0;i<dataList.size();i++)
               {
                  if(dataList.get(i).userId==brostcastId)
                  {
                      dataList.remove(i);
                      break;
                  }
               }
            }
            else //如果是主播 视频不优先 获取所有列表
            {
                for(int i=0;i<dataList.size();i++)
                {
                    if(dataList.get(i).userId==brostcastId)
                    {
                       dataList.remove(i);
                       break;
                    }
                }

                VideoData data =new VideoData();
                data.userId = brostcastId;
                data.viewType = MeetingConfig.TYPE_VIDEO;
                data.userType = MeetingConfig.BROADCASTER_TYPE;
                data.viewName= "";
                dataList.add(0,data);
            }
        }
        else
        {
            //如果不是主播 视频优先 获取获取除主播外的所有列表，
            if(videoFirst)
            {
                for(int i=0;i<dataList.size();i++)
                {
                    int itemId = dataList.get(i).userId;
                    if(itemId==brostcastId || itemId == userId)
                    {
                        dataList.remove(i);
                        i--;
                        continue;
                    }
                }

                VideoData data =new VideoData();
                data.userId = userId;
                data.viewType =MeetingConfig.TYPE_VIDEO;
                data.userType = MeetingConfig.AUDIENCE_TYPE;
                data.viewName= "";
                dataList.add(0,data);
            }
            else //如果不是主播 视频不优先 获取获播外的所有列表
            {
                for(int i=0;i<dataList.size();i++)
                {
                    int itemId = dataList.get(i).userId;
                    if(itemId==brostcastId || itemId == userId)
                    {
                        dataList.remove(i);
                        i--;
                        continue;
                    }
                }

                VideoData dataId =new VideoData();
                dataId.userId = brostcastId;
                dataId.viewType =MeetingConfig.TYPE_VIDEO;
                dataId.userType = MeetingConfig.BROADCASTER_TYPE;
                dataId.viewName= "";
                dataList.add(0,dataId);

                VideoData data =new VideoData();
                data.userId = userId;
                data.viewType =MeetingConfig.TYPE_VIDEO;
                data.userType = MeetingConfig.AUDIENCE_TYPE;
                data.viewName= "";
                dataList.add(1,data);
            }
        }
        return dataList;
    }

    private List<VideoData> getAllVideoDataList()
    {
        List<VideoData> dataList = new ArrayList<>();

        for (HashMap.Entry<Integer, Integer> pair : mUserMap.entrySet()) {
            VideoData data = new VideoData();
            data.viewType =MeetingConfig.TYPE_VIDEO;
            data.viewName ="";
            data.userType = pair.getValue();
            data.userId = pair.getKey();
            dataList.add(data);
        }
        return  dataList;
    }

    public void destory()
    {
        destoryRTC();
        lougout();
        clearUserMap();
        clearMsg();
        mReadNum = 0;
    }

    public void addMsgItem(String name,String msg)
    {
        MsgItem item = new MsgItem(name,msg);
        mMsgList.add(item);
    }

    private int mReadNum = 0;
    public void setReadNum(int num)
    {
        mReadNum =num;
    }

    public int getReadNum()
    {
        return mReadNum;
    }

    public List<MsgItem> getMsgList()
    {
        return mMsgList;
    }

    public void clearMsg()
    {
        mMsgList.clear();
    }

    public void clearUserMap()
    {
        mUserMap.clear();
    }

    public void destoryRTC(){
        if(mRtcEngine!=null)
        {
            RtcEngine.destroy();
//            mRtcEngine.destroy();
            mRtcEngine =null;
        }
    }

    public void lougout(){
        if(mAgoraSigAPI!=null)
        {
            mAgoraSigAPI.logout();
            mAgoraSigAPI =null;
        }
    }

}
